﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Composite.Regions;
using Jbe.TestSuite.Infrastructure.Interface;
using Jbe.Composite.Extensions;
using Jbe.TestSuite.Infrastructure.Interface.Documents;
using Jbe.TestSuite.CodeEditor.Domain;
using Jbe.TestSuite.CodeEditor.Properties;
using System.Windows.Controls;
using Jbe.TestSuite.CodeEditor.Interface;
using ICSharpCode.AvalonEdit.CodeCompletion;
using ICSharpCode.AvalonEdit.Folding;
using ICSharpCode.AvalonEdit.Highlighting;
using Microsoft.Win32;
using Jbe.TestSuite.CodeEditor.Completion;
using Jbe.TestSuite.CodeEditor.Completion.Demain;
using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Document;
using System.Text.RegularExpressions;
using System.Threading;

namespace Jbe.TestSuite.CodeEditor.Applications
{
    internal class ModuleController
    {
        private readonly IApplicationContainer container;
        private readonly IRegionManager regionManager;
        private readonly IUIElementCreationService uiElementCreationService;
        private readonly IDocumentManager documentManager;
        private readonly RsenseService rsenseService;

        private readonly DelegateCommand commpletionCommand;

        public ModuleController(IApplicationContainer container, IRegionManager regionManager, IUIElementCreationService uiElementCreationService, IDocumentManager documentManager)
        {
            this.container = container;
            this.regionManager = regionManager;
            this.uiElementCreationService = uiElementCreationService;
            this.documentManager = documentManager;
            this.rsenseService = new RsenseService(@"M:\piston\lib\piston\plugin\completion\rsense-0.3");
            this.commpletionCommand = new DelegateCommand(Completion, CanCompletion);
            CodeEditorCommands.Completion.RegisterCommand(commpletionCommand);
        }

        public void Initialize()
        {
            IToolBarItem toolBarItem = uiElementCreationService.CreateToolBarItem(
                Resources.CodeEditor, Resources.SignalVisualizer.ToBitmap());
            toolBarItem.Click += ShowVisualizerClick;
            IToolBar toolBar = uiElementCreationService.CreateToolBar(toolBarItem);
            regionManager.Regions[ShellRegionNames.ToolBarTray].Add(toolBar);

            ToolBar myToolBar = new ToolBar();

            regionManager.Regions[ShellRegionNames.ToolBarTray].Add(myToolBar as ToolBar);

            documentManager.Register(container.Resolve<CodeDocumentType>());
            //documentManager.Register(container.Resolve<XpsExpo吗rtDocumentType>());

            container.Resolve<DocumentController>().Initialize();
        }

        private void ShowVisualizerClick(object sender, EventArgs e)
        {
            if (documentManager.ActiveDocument != null)
            {
                string file = documentManager.ActiveDocument.FileName;
                ProcessService processService = new ProcessService();
                processService.Run(file);
            }
        }

        private void Completion(object param) { Completion(param as TextEditor); }

        public void Completion(TextEditor textEditor)
        {
            this.rsenseService.Run();

            using (StreamWriter writer = new StreamWriter("D:\\important.rb"))
            {
                writer.Write(textEditor.Text);
            }

            int offset = textEditor.SelectionStart;
            string prefix = Utilities.WordBeforeCaret(textEditor);

            TextLocation location = textEditor.Document.GetLocation(offset);
            int col = location.Column - prefix.Length - 2;
            if (col < 0)
            {
                col = 0;
            }

            string loc = location.Line.ToString() + ":" + col.ToString();

            this.rsenseService.complete("D:\\important.rb", loc, prefix);

            Thread.Sleep(200);

            Regex r = new Regex(@"completion: (\S+)", RegexOptions.IgnoreCase | RegexOptions.Multiline);  


            MatchCollection matchCollection = r.Matches(this.rsenseService.Buffer);  
            
            

            // open code completion after the user has pressed dot:
            var completionWindow = new CompletionWindow(textEditor.TextArea);
            // provide AvalonEdit with the data:
            IList<ICompletionData> data = completionWindow.CompletionList.CompletionData;
            data.Add(new CodeCompletionData("Item1"));
            data.Add(new CodeCompletionData("Item2"));
            data.Add(new CodeCompletionData("Item3"));
            data.Add(new CodeCompletionData("Another item"));

            foreach (Match m in matchCollection)
            {
                for (int i = 0; i < m.Groups.Count; i++)
                {
                    Group group = m.Groups[i];
                    for (int j = 0; j < group.Captures.Count; j++)
                    {
                        Capture capture = group.Captures[j];
                        data.Add(new CodeCompletionData(capture.Value));
                    }
                }  
            }

            completionWindow.Show();
            completionWindow.Closed += delegate
            {
                completionWindow = null;
            };
        }

        private bool CanCompletion(object param) { return true; }
    }
}
